<script setup lang="ts">
// import { GetParkSysUserDataAPI } from '@/apis/system';
// import type { GetParkSysUserParams } from '@/types/system';
import { delRoleAPI, getPermissionAllTreeAPI, getRoleDetailAPI, getRoleListAPI, getRoleUserAPI } from '@/apis/system';
import type { PageParams, Role, RoleUser, RowChild } from '@/types/system';
import { ref } from 'vue';
import userIcon from '@/assets/user.svg'
import userIconActive from '@/assets/user-active.svg'
import { ElMessage, ElMessageBox, type TreeInstance } from 'element-plus';

// const params = ref<GetParkSysUserParams>({
//   name:'',
//   pageSize:'',
//   page:''
// })
// 获取用户列表
// const getUserList = async()=>{
//   const res =  GetParkSysUserDataAPI(params.value)
//   console.log('获取用户列表',res)
// }

// getUserList()


// 全局rowId
const AllrowId = ref<string>('')
const roleList = ref<Role[]>([])
    const getRoleList = async()=>{
      const res = await getRoleListAPI()
      console.log('获取角色列表',res)
      roleList.value = res.data

      // 获取第一个角色详情
      const roleId = roleList.value[0].roleId
      // 将角色id赋值给 全局rowid
      AllrowId.value = roleId
      getRoleDetail(Number(roleId))
      // 获取角色成员列表
      getRoleUserList(roleId)
    }
  getRoleList()


  const treeList  = ref<RowChild[]>([])
// 获取所有权限列表
const getAllTree = async() =>{
  const res = await getPermissionAllTreeAPI()
  console.log('获取所有权限列表',res)
  treeList.value = res.data
  
}
getAllTree()

// 获取角色详情
const perms = ref<number[][]>([]) //当前角色权限列表

// 注意这里是数组
const treeRefs = ref<TreeInstance[]>([])

// 成员数量
const userTotal = ref(0)
// 封装请求方法
const getRoleDetail = async (rowId:number) =>{
  const res = await getRoleDetailAPI(Number(rowId))
  console.log('根据当前 roleId 获取权限点列表',res)
  perms.value = res.data.perms
  userTotal.value = res.data.userTotal  ?? 0

  // 切换时，重新设置树形组件选中
  treeRefs.value.forEach((tree:TreeInstance,index:number)=>{
    tree.setCheckedKeys(perms.value[index])
  })
}

  // 点击激活交互
  const activeIndex = ref(0)
  const changeRole = (index:number,rowId:string) =>{
    // 设置高度效果
    activeIndex.value = index
    // 获取角色详情
    getRoleDetail(Number(rowId))
         // 获取角色成员列表
      getRoleUserList(rowId)

        // 将角色id赋值给 全局rowid
      AllrowId.value = rowId

  }


  // tabs 切换
  const activeTabName = ref<'tree' | 'member' >('tree')

  // 获取角色列表
  // 总条数
   const total = ref(0)
  //  请求params参数
  const params = ref<PageParams>({
    page:1,
    pageSize:2
  })
  const roleUserList = ref<RoleUser[]>([])
  const getRoleUserList = async (rowId:string) =>{
  const res = await getRoleUserAPI(rowId,params.value)
  console.log('获取角色列表',res)
  roleUserList.value = res.data.rows
  total.value = res.data.total
  }

  // 页码或者页数改变时重新发送请求
  const getRoleUserListChange = () =>{
    getRoleUserList(AllrowId.value)
  }


// 删除角色
const delRole = (id:string) =>{
  // 提示用户

  ElMessageBox.confirm(
    '是否确认删除当前角色',
    '温馨提示',
    {
      confirmButtonText:'确定',
      cancelButtonText:'取消',
      type:'warning'
    }) .then(async()=>{
       const res = await delRoleAPI(id)
     console.log('删除角色',res)
       // 删除下之后刷新角色列表
  getRoleList()
   ElMessage.success('删除成功！')

    }).catch(()=>{

    })
 
}
</script>

<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div class="role-item" v-for="(item,index) in roleList" :key="item.roleId"
        :class="{ active : index === activeIndex }" 
        @click="changeRole(index,item.roleId)"
      >
        <div class="role-info">
          <img :src=" activeIndex === index ? userIconActive : userIcon" class="icon" />
          {{ item.roleName }}
        </div>
        <div class="more" >
          <!-- <img src="@/assets/more.svg" class="icon" /> -->
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
            <img src="@/assets/more.svg" class="icon" />
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push(`/addRole/${item.roleId}`)">
                  <el-button link>编辑角色</el-button>
                </el-dropdown-item>
                <el-dropdown-item @click="delRole(item.roleId)">
                  <el-button type="danger"  link>删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <el-button class="addBtn" size="small" @click="$router.push('/addRole')">添加角色</el-button>
    </div> 
    <!-- 右侧权限和成员 -->
     <div class="right-wrapper">
      <el-tabs v-model="activeTabName" >
        <el-tab-pane label="功能权限" name="tree">
            <div class="tree-wrapper">
        <!-- 角色权限列表 -->
         <div v-for="(item,index) in treeList " :key="item.id" class="tree-item">
          <div class="tree-title">{{ item.title }}</div>
          <!-- 树形组件 -->
           <el-tree :data="item.children" :props="{label : 'title', disabled : () =>true}" 
           default-expand-all  show-checkbox  
           :default-checked-keys="perms[index]"
           node-key="id"
           ref="treeRefs"
           ></el-tree>
         </div>
      </div>
       </el-tab-pane>
       <el-tab-pane :label="`成员(${userTotal})`" name="member">
          <div class="user-wrapper">
            <el-table :data="roleUserList" width="100%" :header-cell-style="{background:'#f4f6f8'}">
              <el-table-column type="index" label="序号" width="250px" />
              <el-table-column  label="员工姓名" prop="name" />
              <el-table-column  label="登录账号" prop="userName" />
            </el-table>
            <div class="elPage">
                <el-pagination
              :total="total"
              :page-sizes="[2,5,10,20]"
              layout="total,  prev, pager,next,sizes,  "
              v-model:current-page="params.page"
              v-model:page-size="params.pageSize"
              @change="getRoleUserListChange()"
            ></el-pagination>
            </div>
       
          </div>
            
       </el-tab-pane>
      </el-tabs>
      
    
     </div>
  </div>
</template>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;

  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
        width: 20px;
      }
    }

    .more {
      display: flex;
      align-items: center;
      .icon {
          width: 15px;
        }
    }

    .addBtn {
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;

        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        } }
      }
    }

    ::v-deep .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;
      height: 500px;
      // background-color: #4770ff;

      .elPage{
        width: 100%;
        display: flex;
        justify-content: end;
        margin-top: 20px;
      }
    }
  }

</style>